import type { AjaxResult, RequestOptions, UniRequestFailResult } from '#/request';

import { UniRequest } from './uniRequest';
import { UniRequestOptions } from './uniTransform';

/** 请求重试机制 */
export class UniRequestRetry {
  /** 重试 */
  async retry(
    error: UniRequestFailResult<AjaxResult>,
    config: UniRequestOptions,
    options: RequestOptions,
    instance: UniRequest,
    fnType: 'upload' | 'download' | 'request',
  ) {
    const { waitTime, count } = options?.retryRequest ?? {};
    (config as any).__retryCount = (config as any).__retryCount || 0;
    if ((config as any).__retryCount >= count) {
      return Promise.reject(error);
    }
    (config as any).__retryCount += 1;
    await this.delay(waitTime);
    switch (fnType) {
      case 'upload':
        return await instance.uploadFile(config, options);
      case 'download':
        return await instance.downloadFile(config, options);
      case 'request':
        return await instance.request(config, options);
    }
  }

  /** 延迟 */
  private delay(waitTime: number) {
    return new Promise((resolve) => setTimeout(resolve, waitTime));
  }
}
